/*
 * @Author: 13938960424 1758142861@qq.com
 * @Date: 2023-11-06 14:50:07
 * @LastEditors: 13938960424 1758142861@qq.com
 * @LastEditTime: 2023-11-09 16:20:53
 * @FilePath: /sjf/new-xshell/muduo/test/http_test/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "../../http/http.hpp"

#define WWWROOT "./wwwroot/"

void split_test()
{
    std::string str = ",,,abc,,,,def,zxc,,,";
    std::vector<std::string> arry;
    Util::Split(str,",",&arry);
    for(auto &e : arry)
    {
        std::cout << "[" << e << "]\n";
    }
}

bool read_file_test()
{
    std::string buff;
    const std::string str = "./main.cc";
    bool ret = Util::ReadFile(str,&buff);
    if(false == ret)
        return false;
    ret = Util::WriteFile("./ttttt",buff);
    //在shell下使用md5sum对ttttt 和 main.cc 进行判断文件内容是否一样
    if(false == ret)
        return false;
    return true;
}

bool URL_test()
{
    std::string str = Util::UrlEncode("123passC  ",true);
    std::cout << str << std::endl;
    std::string res = Util::UrlDeCode(str,true);
    std::cout << res << std::endl;
}

void Desc_test()
{
    std::cout << Util::StatuDesc(200) << std::endl;
    std::cout << Util::ExtMime("a.docx") << std::endl;
}

void Path_test()
{
    std::cout << Util::ValidPath("html/../../index.html") << std::endl;
}

std::string RequestStr(const HttpRequest &req) {
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void Login(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void PutFile(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}
void DelFile(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
int main()
{
    HttpServer server(8085);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);//设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Listen();
    return 0;
}